#include "header.hpp"
using namespace std;

//class mutex (mutual exclusion)
//lock_guard: unlock automatically
//unique_lock: flexible
int global = 0;
mutex mtx;

//RAII: manage resource by stack object's lifetime
//In this instance, RAII uses to automatically unlock the mutex
class MutexLock{
public:
    //lock mutex in constructor
    MutexLock(mutex& mutx)
    : _mutx(mutx)
    {
        _mutx.lock();
    }

    //unlock mutex in destructor
    ~MutexLock(){
        _mutx.unlock();
    }

private:
    mutex& _mutx;
};

void threadFunc2(){
    for(size_t i = 0; i != 1000000; ++i){
        MutexLock autoLock(mtx);
        //function of lock_guard is similar to the customize class MutexLock
        //class lock_guard doesn't provide extra operations of lock and unlock

        //lock_guard<mutex> lg(mtx);
        ++global;
    }
}

void test10(){
    thread t1(threadFunc2);
    thread t2(threadFunc2);

    t1.join();
    t2.join();

    cout << "global = " << global << endl;
}
